<template>
  <div class="transaction-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-actions">
            <el-input v-model="searchKeyword" placeholder="搜索交易对方/订单号" prefix-icon="el-icon-search"
              style="width: 300px; margin-right: 10px;" @input="handleConditionChange" clearable></el-input>
            <label style="margin-right: 5px;">交易时间:</label>
            <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" style="width: 400px; margin-right: 10px;" @change="handleConditionChange"
              value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            
            <!-- 快速时间范围选择 -->
            <div style="display: flex; gap: 5px; margin-right: 10px;">
              <el-button 
                :type="quickDateRange === 'today' ? 'primary' : 'default'"
                @click="setQuickDateRange('today')">今天</el-button>
              <el-button 
                :type="quickDateRange === 'week' ? 'primary' : 'default'"
                @click="setQuickDateRange('week')">最近一周</el-button>
              <el-button 
                :type="quickDateRange === 'month' ? 'primary' : 'default'"
                @click="setQuickDateRange('month')">最近一月</el-button>
              <el-button 
                :type="quickDateRange === 'halfYear' ? 'primary' : 'default'"
                @click="setQuickDateRange('halfYear')">最近半年</el-button>
              <el-button 
                :type="quickDateRange === 'year' ? 'primary' : 'default'"
                @click="setQuickDateRange('year')">最近一年</el-button>
            </div>
            <el-select v-model="filterPlatform" placeholder="选择平台" style="width: 120px; margin-right: 10px;"
              @change="handleConditionChange">
              <el-option label="全部平台" value=""></el-option>
              <el-option label="微信" :value="1"></el-option>
              <el-option label="支付宝" :value="2"></el-option>
            </el-select>
            <el-select v-model="filterIncomeExpense" placeholder="选择类型" style="width: 120px; margin-right: 10px;"
              @change="handleConditionChange">
              <el-option label="全部类型" value=""></el-option>
              <el-option label="收入" :value="1"></el-option>
              <el-option label="支出" :value="2"></el-option>
              <el-option label="不计收支" :value="3"></el-option>
            </el-select>
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px;">
              查询
            </el-button>
            <el-button @click="resetFilters" style="margin-left: 10px;">
              重置
            </el-button>
          </div>
        </div>
      </template>

      <div class="table-wrapper">
        <div style="height: calc(100vh - 350px); overflow-y: auto;">
          <el-table v-loading="loading" :data="transactions" style="width: 100%" fit>
            <el-table-column prop="paymentPlatform" label="平台" min-width="60">
              <template slot-scope="scope">
                <span>{{ scope.row.paymentPlatform === 2 ? '支付宝' : '微信' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="transactionTime" label="交易时间" min-width="160">
              <template slot-scope="scope">
                <span>{{ formatDate(scope.row.transactionTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="transactionOrderNumber" label="订单号" min-width="180"></el-table-column>
            <el-table-column prop="merchantOrderNumber" label="商户订单号" min-width="180"></el-table-column>
            <el-table-column prop="productDescription" label="商品描述" min-width="160"></el-table-column>
            <el-table-column prop="transactionCategory" label="交易分类"></el-table-column>
            <el-table-column prop="transactionPartner" label="交易对方" min-width="160"></el-table-column>
            <el-table-column prop="incomeExpense" label="收支类型" min-width="80">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.incomeExpense === 1" type="success">收入</el-tag>
                <el-tag v-else-if="scope.row.incomeExpense === 2" type="danger">支出</el-tag>
                <el-tag v-else type="info">不计收支</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="paymentMethod" label="支付方式" min-width="80"></el-table-column>
            <el-table-column prop="amount" label="金额" min-width="100" align="right">
              <template slot-scope="scope">
                <span :class="{ 'income': scope.row.incomeExpense === 1 }">
                  {{ scope.row.incomeExpense === 1 ? '+' : '' }}{{ scope.row.amount }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="transactionStatus" label="交易状态" min-width="80"></el-table-column>
            <el-table-column prop="remarks" label="备注" min-width="200"></el-table-column>

          </el-table>
        </div>

        <div class="summary-section">
          <div class="summary-item">
            <span class="summary-label">收入合计：</span>
            <span class="summary-amount income">+{{ totalIncome }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">支出合计：</span>
            <span class="summary-amount expense">{{ totalExpense }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">净金额：</span>
            <span :class="['summary-amount', 'net', { 'income': netAmount > 0, 'expense': netAmount < 0 }]">
              {{ netAmount >= 0 ? '+' : '' }}{{ netAmount }}
            </span>
          </div>
        </div>

        <div class="pagination">
          <el-pagination v-model="currentPage" v-model:page-size="pageSize" :page-sizes="[50, 100, 500, 1000, 2000]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>


    </el-card>
  </div>
</template>

<script>
import { transactionService } from '@/api/transactionService'

export default {
  name: 'TransactionList',
  data() {
    return {
      loading: false,
      transactions: [],
      total: 0,
      currentPage: 1,
      pageSize: 50,
      searchKeyword: '',
      filterPlatform: '',
      filterIncomeExpense: '',
      dateRange: null,
      quickDateRange: '', // 快速时间范围：today, week, month, halfYear, year
      searchTimer: null
    }
  },

  mounted() {
    this.loadTransactions()
  },
  computed: {
    totalIncome() {
      // 计算收入总额（收支类型为1表示收入）
      return this.transactions
        .filter(item => item.incomeExpense === 1)
        .reduce((sum, item) => sum + (Number(item.amount) || 0), 0)
        .toFixed(2)
    },
    totalExpense() {
      // 计算支出总额（收支类型为2表示支出）
      return this.transactions
        .filter(item => item.incomeExpense === 2)
        .reduce((sum, item) => sum + (Number(item.amount) || 0), 0)
        .toFixed(2)
    },
    netAmount() {
      // 计算净金额（收入-支出）
      return (this.totalIncome - this.totalExpense).toFixed(2)
    }
  },

  methods: {
    handleConditionChange() {
      // 防抖处理，避免频繁请求
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.searchTimer = setTimeout(() => {
        this.currentPage = 1
        this.loadTransactions()
      }, 300)
    },
    handleSearch() {
      this.currentPage = 1 // 搜索时重置到第一页
      this.loadTransactions()
    },
    resetFilters() {
      this.searchKeyword = ''
      this.filterPlatform = ''
      this.filterIncomeExpense = ''
      this.dateRange = null
      this.quickDateRange = ''
      this.currentPage = 1
      this.loadTransactions()
    },
    
    // 设置快速时间范围
    setQuickDateRange(type) {
      this.quickDateRange = type
      const now = new Date()
      const endTime = new Date(now)
      endTime.setHours(23, 59, 59, 999)
      
      const startTime = new Date()
      
      switch(type) {
        case 'today':
          // 今天：从00:00:00到23:59:59
          startTime.setHours(0, 0, 0, 0)
          break
        case 'week':
          // 最近一周：从7天前的00:00:00到今天的23:59:59
          startTime.setDate(now.getDate() - 7)
          startTime.setHours(0, 0, 0, 0)
          break
        case 'month':
          // 最近一个月：从30天前的00:00:00到今天的23:59:59
          startTime.setDate(now.getDate() - 30)
          startTime.setHours(0, 0, 0, 0)
          break
        case 'halfYear':
          // 最近半年：从180天前的00:00:00到今天的23:59:59
          startTime.setDate(now.getDate() - 180)
          startTime.setHours(0, 0, 0, 0)
          break
        case 'year':
          // 最近一年：从365天前的00:00:00到今天的23:59:59
          startTime.setDate(now.getDate() - 365)
          startTime.setHours(0, 0, 0, 0)
          break
      }
      
      // 格式化为yyyy-MM-dd HH:mm:ss
      const formatDateTime = (date) => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      
      this.dateRange = [formatDateTime(startTime), formatDateTime(endTime)]
      this.currentPage = 1
      this.loadTransactions()
    },
    loadTransactions() {
      this.loading = true
      // 构建查询参数
      const params = {
        page: this.currentPage || 1,
        size: this.pageSize || 50,
        keyword: this.searchKeyword || null,
        platform: this.filterPlatform ? parseInt(this.filterPlatform) : null,
        incomeExpense: this.filterIncomeExpense ? parseInt(this.filterIncomeExpense) : null,
        startTime: this.dateRange ? this.dateRange[0] : null,
        endTime: this.dateRange ? this.dateRange[1] : null
      }

      transactionService.getTransactions(params)
        .then(response => {
          // 确保this.transactions始终是数组类型
          this.transactions = Array.isArray(response.list) ? response.list : []
          // 确保total是数字类型，使用后端返回的total字段
          this.total = typeof response.total === 'number' ? response.total : 0

          // 调试信息
          console.log('后端返回数据:', response)
        })
        .catch(error => {
          this.$message.error('获取交易记录失败')
          console.error(error)
          // 出错时设置为空数组，避免迭代错误
          this.transactions = []
          this.total = 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.loadTransactions()
    },
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadTransactions()
    },


    formatDate(dateString) {
      if (!dateString) return ''
      // 创建Date对象，解析UTC时间
      const date = new Date(dateString)

      // 获取UTC时间的各个部分并加上8小时（转换为UTC+8）
      let year = date.getUTCFullYear()
      let month = date.getUTCMonth() + 1
      let day = date.getUTCDate()
      let hours = date.getUTCHours() + 8
      let minutes = date.getUTCMinutes()
      let seconds = date.getUTCSeconds()

      // 处理小时可能超过24的情况
      if (hours >= 24) {
        hours -= 24
        // 创建一个新的日期对象来处理日期变更
        const tempDate = new Date(Date.UTC(year, month - 1, day))
        tempDate.setDate(tempDate.getDate() + 1)
        year = tempDate.getUTCFullYear()
        month = tempDate.getUTCMonth() + 1
        day = tempDate.getUTCDate()
      }

      // 格式化输出
      return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.transaction-list {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  min-height: 120px;
}

.header-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  padding: 10px 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-start;
}

:deep(.income) {
  color: #67c23a;
  font-weight: bold;
}

.table-wrapper {
  height: calc(100vh - 320px);
  display: flex;
  flex-direction: column;
}

.summary-section {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-top: 0;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.summary-item {
  margin-right: 30px;
  display: flex;
  align-items: center;
}

.summary-label {
  font-weight: 500;
  margin-right: 8px;
  color: #606266;
}

.summary-amount {
  font-size: 16px;
  font-weight: bold;
  min-width: 100px;
  text-align: right;
}

:deep(.summary-amount.expense) {
  color: #f56c6c;
}

:deep(.summary-amount.net) {
  font-size: 18px;
}
</style>